<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        position: absolute;
        top: 0;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>

    <script>
      //拖拽三剑客 ： mousedown mousemove mouseup
      var box = document.getElementById('box');
      //得到box样式
      var cssStyle = getComputedStyle(box, null);
      console.log(cssStyle.width);
      box.addEventListener('mousedown', function () {
        console.log('down');
        //在谁身上移动就给谁绑定移动事件，在把移动坐标赋值给box
        document.addEventListener('mousemove', fn);
        function fn(event) {
          var X = event.clientX;
          var Y = event.clientY;

          //样式表是字符串，需转化为数字
          box.style.top = Y - parseInt(cssStyle.height) / 2 + 'px';
          box.style.left = X - parseInt(cssStyle.width) / 2 + 'PX';
        }
        box.addEventListener('mouseup', function () {
          document.removeEventListener('mousemove', fn);
        });
      });
    </script>
  </body>
</html>
